package com.by_man.presenter.module_health_records.upload_health_records;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_health_records.image.AllImages;
import com.by_man.presenter.module_health_records.image.BitmapManager;
import com.by_man.presenter.module_health_records.image.BucketImgList;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * Created by man on 2017-03-04.
 */
public class AlbumActivity extends AppCompatActivity {
    private ArrayList<BucketImgList> buckets;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album);
        AllImages allImages = AllImages.getInstance();
        buckets = allImages.getAllImgs(false);
        initView();
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, UploadHealthRecordsActivity.class);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode, event);
//    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        startActivity(intent);
//    }

    private void initView() {
        Button cancel = (Button) findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(AlbumActivity.this, UploadHealthRecordsActivity.class);
//                startActivity(intent);
                onBackPressed();
            }
        });

        GridView gridView = (GridView)findViewById(R.id.fileGridView);
        GridViewAdapter adapter = new GridViewAdapter();
        gridView.setAdapter(adapter);
    }

    private class GridViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return buckets.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position,View convertView,ViewGroup parent) {
            ViewHolder viewHolder;
            if (null == convertView) {
                convertView = getLayoutInflater().inflate(R.layout.item_gridview_album, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.backImage = (ImageView) convertView.findViewById(R.id.file_back);
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.file_image);
                viewHolder.choose_back = (ImageView) convertView.findViewById(R.id.choose_back);
                viewHolder.fileNum = (TextView)convertView.findViewById(R.id.filenum);
                viewHolder.folderName = (TextView)convertView.findViewById(R.id.name);
                viewHolder.imageView.setAdjustViewBounds(true);
                viewHolder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                convertView.setTag(viewHolder);
            }
            viewHolder = (ViewHolder)convertView.getTag();
            viewHolder.folderName.setText(buckets.get(position).bucketName);
            viewHolder.fileNum.setText("" + buckets.get(position).count);
            final int p = position;
            viewHolder.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(AlbumActivity.this, AllPhotoOfAlbumActivity.class);
                    intent.putExtra("position", p);
                    startActivity(intent);
                }
            });
            loadImage(position, viewHolder.imageView);
            return convertView;
        }

        private class ViewHolder {
            public ImageView backImage;
            public ImageView imageView;
            public ImageView choose_back;
            public TextView folderName;
            public TextView fileNum;
        }

        /***********************************************************
         * 异步加载
         ***********************************************************/
        private class AsyncImageLoader extends AsyncTask<Integer, Void, Bitmap> {
            public int position;
            private final WeakReference<ImageView> imageViewWeakReference;

            public AsyncImageLoader(ImageView imageView){
                imageViewWeakReference = new WeakReference<ImageView>(imageView);
            }

            @Override
            protected Bitmap doInBackground(Integer...params) {
                position = params[0];
                String imgPath = buckets.get(position).imgList.get(0).imagePath;
                String thumbnailPath = buckets.get(position).imgList.get(0).thumbnailPath;
                Bitmap bitmap;
                if (null == thumbnailPath) {
                    bitmap = BitmapManager.getCompressBitmap(imgPath, 200,200);
                } else {
                    bitmap = BitmapManager.getCompressBitmap(thumbnailPath,200,200);
                    if (null == bitmap) {
                        bitmap = BitmapManager.getCompressBitmap(imgPath,200,200);
                    }
                }
                BitmapManager.putBitmap(imgPath,bitmap);
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap){
                if (imageViewWeakReference != null && bitmap != null) {
                    ImageView imageView = imageViewWeakReference.get();
                    imageView.setImageBitmap(bitmap);
                }
            }
        }

        public AsyncImageLoader getAsyncImageLoader(ImageView imageView) {
            WeakReference<AsyncImageLoader> info = (WeakReference<AsyncImageLoader>) imageView.getTag();
            if (info != null) {
                return info.get();
            }
            return null;
        }

        public boolean cancelAsyncWork(int position, ImageView imageView) {
            AsyncImageLoader imageLoader = getAsyncImageLoader(imageView);
            if (null != imageLoader) {
                if (imageLoader.position != position) {
                    imageLoader.cancel(true);
                } else {
                    return false;
                }
            }

            return true;
        }

        public void loadImage(int position,ImageView imageView) {
            String imgPath = buckets.get(position).imgList.get(0).imagePath;
            String thumbnailPath = buckets.get(position).imgList.get(0).thumbnailPath;
            Bitmap bitmap = BitmapManager.getBitmap(imgPath);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                if (cancelAsyncWork(position, imageView)) {
                    AsyncImageLoader imageLoader = new AsyncImageLoader(imageView);
                    WeakReference<AsyncImageLoader> loaderWeakReference = new WeakReference<AsyncImageLoader>(imageLoader);
                    imageView.setTag(loaderWeakReference);
                    imageLoader.execute(position);
                }
            }
        }
    }
}
